//
//  BCShopViewController.m
//  BangcaiBuy
//
//  Created by lsy on 16/6/13.
//  Copyright © 2016年 BCB. All rights reserved.
//

#import "BCShopViewController.h"
#import "ShopGroup.h"
#import "BCStuffChooseViewController.h"
#import "BCClassEnterCell.h"
#import "BCBannerCell.h"
#import "BCNiceStuffCollectionViewCell.h"
#import "BCAlwaysBuyCollectionViewCell.h"
#import "BCWeatherCollectionViewCell.h"
#import "BCNiceStuffTitleCollectionViewCell.h"
#import "BCSearchResulfViewController.h"
#import "BCStuffInfoViewController.h"
#import "BCRefreshGifHeader.h"
#import "BCMessageViewController.h"

@interface BCShopViewController () <UICollectionViewDataSource,UICollectionViewDelegate,BCBannerCellDelegate>
@property (nonatomic, strong) UICollectionView *collectionView;
/** 搜索框绿色渐变背景视图 */
@property (nonatomic, strong) UIView *greenView;
/** 搜索框新消息小红点视图 */
@property (nonatomic, strong) UIView *msgReddotView;
/** 搜索view */
@property (nonatomic, strong) UIView *searchView;
/** 组的集合 */
@property (nonatomic, strong) NSMutableArray *groups;
/** 特惠与新品切换标示 */
@property (nonatomic, assign) NSInteger segFlag;
/** 城市 */
@property (nonatomic, strong) UILabel *cityLabel;
/** 商品数据 */
@property (nonatomic, strong) NSArray *stuffArray;

@property (nonatomic, assign) BOOL bannerRefreshFlag;
@end

@implementation BCShopViewController

-(void)viewDidLoad {
    [super viewDidLoad];
}

-(void)getView {
    [self p_initNavgationBar];
    [self p_initMain];
    [self p_initTopView];
    [self p_initSearchView];
    [self p_initStuffData];
    [self updateCity:@"大连"];
    [self initData]; //初始化数据
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.view.backgroundColor = [UIColor whiteColor];
    //隐藏导航栏
    self.navigationController.navigationBar.hidden = YES;
    _bannerRefreshFlag = YES;
    [[BCShopCarManager sharedInstance] hideShopWindow];
    if (self.rdv_tabBarController.tabBarHidden) {
        [[self rdv_tabBarController] setTabBarHidden:NO animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private
/**
 *  初始化商品数据
 */
-(void)p_initStuffData {
//    //临时
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    hud.mode = MBProgressHUDModeIndeterminate;
//    hud.labelText = @"稍等一下，邦采立现！";
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [MBProgressHUD hideHUDForView:self.view animated:YES];
//    });
    [BCShopViewManager loadDataToStuff];
    self.stuffArray = [BCShopViewManager readSpecialOfferStuffs];
}

/**
 *  初始化导航栏
 */
-(void)p_initNavgationBar {
}

/**
 *  初始化主视图view
 */
- (void)p_initMain {
    UICollectionViewFlowLayout *flowLayout= [[UICollectionViewFlowLayout alloc]init];
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, SCREEN_HEIGHT) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor colorWithRed:244.f/255.f green:244.f/255.f blue:244.f/255.f alpha:1];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.collectionView];
    //设置contentInset属性（上左下右的值）
    self.collectionView.contentInset = UIEdgeInsetsMake(45, 0, 0, 0);
    //注册collectionView组头
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"kHeaderID"];
    
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
    BCRefreshGifHeader *header = [BCRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    header.backgroundColor = [UIColor clearColor];
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    header.automaticallyChangeAlpha = YES;
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    // 隐藏状态
    header.stateLabel.hidden = YES;
    // 马上进入刷新状态
//    [header beginRefreshing];
    self.collectionView.mj_header = header;
    self.segFlag = 1;
}

#pragma mark 下拉刷新数据
- (void)loadNewData
{
    sleep(3);
    _bannerRefreshFlag = YES;
    [_collectionView reloadData];
    [self.collectionView.mj_header endRefreshing];
}

/**
 *  初始化顶部视图view
 */
- (void)p_initTopView {
    self.greenView.frame = CGRectMake(0, 0, self.view.frame.size.width , 65);
    self.greenView.backgroundColor = BangcaiGreen;
    self.greenView.alpha = 0.95f;
    [self.view addSubview:self.greenView];
}

/**
 *  初始化搜索框view
 */
- (void)p_initSearchView {
    
    UIFont *cityStringFont = [UIFont boldSystemFontOfSize:15.f];
    NSDictionary *attrs = @{NSFontAttributeName : cityStringFont};
    CGSize cityStringSize = [@"俩字" boundingRectWithSize:CGSizeMake(65.f, 20.f) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
    self.cityLabel = [[UILabel alloc] initWithFrame:CGRectMake(5.f, 35.f, 45.f, cityStringSize.height)];
    self.cityLabel.backgroundColor = [UIColor clearColor];
    self.cityLabel.text = @"city";
    self.cityLabel.font = cityStringFont;
    self.cityLabel.textColor = [UIColor whiteColor];
    self.cityLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
    self.cityLabel.textAlignment = NSTextAlignmentCenter;
    [self.greenView addSubview:self.cityLabel];
    
    UIView *searchBar = [[UIView alloc] initWithFrame:CGRectMake(self.cityLabel.frame.origin.x*2+self.cityLabel.frame.size.width, 0, self.greenView.frame.size.width-(55.f*2), 30.f)];
    searchBar.center = CGPointMake(self.view.center.x, self.cityLabel.center.y);
    searchBar.backgroundColor = [UIColor colorWithRed:0/255.f green:162.f/255.f blue:72.f/255.f alpha:1];
    searchBar.layer.cornerRadius = 8.f;
    [self.greenView addSubview:searchBar];
    
    UIImageView *searchIconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"搜索"]];
    searchIconView.frame = CGRectMake((searchBar.frame.size.width-15.f-cityStringSize.width-2.f)/2, 8.f, 15.f, 15.f);
    [searchBar addSubview:searchIconView];
    
    UILabel *tipLable = [[UILabel alloc] initWithFrame:CGRectMake(searchIconView.frame.origin.x+searchIconView.frame.size.width+2.f, 0, cityStringSize.width, searchBar.frame.size.height)];
    tipLable.text = @"邦采";
    tipLable.backgroundColor = [UIColor clearColor];
    tipLable.font = cityStringFont;
    tipLable.textAlignment = NSTextAlignmentLeft;
    tipLable.textColor = [UIColor whiteColor];
    [searchBar addSubview:tipLable];
    
    UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    searchButton.frame = CGRectMake(searchBar.frame.origin.x, 0, searchBar.frame.size.width, self.greenView.frame.size.height);
    searchButton.backgroundColor = [UIColor clearColor];
    [searchButton addTarget:self action:@selector(p_startSearch) forControlEvents:UIControlEventTouchUpInside];
    [self.greenView addSubview:searchButton];
    
    UIImageView *msgImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"消息"]];
    msgImageView.frame = CGRectMake(_greenView.frame.size.width-cityStringSize.height-20.f, 35.f, cityStringSize.height, cityStringSize.height);
    [_greenView addSubview:msgImageView];
    
    CGFloat msgReddotWidth = 8.f;
    _msgReddotView = [[UIView alloc] initWithFrame:CGRectMake(_greenView.frame.size.width-20.f-msgReddotWidth, msgImageView.frame.origin.y-3.f, msgReddotWidth, msgReddotWidth)];
    _msgReddotView.layer.cornerRadius = _msgReddotView.frame.size.height*0.5f;
    _msgReddotView.backgroundColor = [UIColor redColor];
//    _msgReddotView.hidden = YES;
    [_greenView addSubview:_msgReddotView];
    
    UIButton *msgButton = [UIButton buttonWithType:UIButtonTypeCustom];
    msgButton.backgroundColor = [UIColor clearColor];
    msgButton.frame = CGRectMake(searchButton.frame.origin.x+searchBar.frame.size.width, 0, SCREEN_WIDTH-searchButton.frame.origin.x-searchBar.frame.size.width, searchButton.frame.size.height);
    [msgButton addTarget:self action:@selector(msgAction:) forControlEvents:UIControlEventTouchUpInside];
    [_greenView addSubview:msgButton];
}

- (void)updateCity:(NSString *)city {
    self.cityLabel.text = city;
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.groups.count;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [[self.groups[section] items] count];
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        static NSString *ID = @"BannerCell";
        BCBannerCell *cell = [BCBannerCell cellWithCollectionView:collectionView];
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
        cell.delegate = self;
        if (_bannerRefreshFlag) {
            [cell p_initScrollView];
        }
        _bannerRefreshFlag = NO;
        return cell;
    }
    else if (indexPath.section == 1) {
        static NSString *ID = @"WeatherCell";
        BCWeatherCollectionViewCell *cell = [BCWeatherCollectionViewCell cellWithCollectionView:collectionView];
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
        //明日日期
        NSDate *tomorrowDate = [BCDateTool GetDayWithIndex:1 From:[NSDate date]];
        cell.dateLable.text = [BCDateTool dateStringFromDate:tomorrowDate];
        cell.weekLable.text = [BCDateTool weekdayStringFromDate:tomorrowDate];
//        cell.weatherLable.text = @"";
//        cell.iconImageView.image = [UIImage imageNamed:@""];
        return cell;
    }
    else if (indexPath.section == 2) {
        static NSString *ID = @"ClassCell";
        BCClassEnterCell *cell = [BCClassEnterCell cellWithCollectionView:collectionView];
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
        if (indexPath.row == 0) {
            cell.titleLable.text = @"禽蛋肉品";
        }
        else if (indexPath.row == 1) {
            cell.titleLable.text = @"蔬菜水果";
        }
        else if (indexPath.row == 2) {
            cell.titleLable.text = @"水产冻品";
        }
        else if (indexPath.row == 3) {
            cell.titleLable.text = @"调料其它";
        }
        else if (indexPath.row == 4) {
            cell.titleLable.text = @"米面粮油";
        }
        else if (indexPath.row == 5) {
            cell.titleLable.text = @"熟食面点";
        }
        else if (indexPath.row == 6) {
            cell.titleLable.text = @"酒水饮料";
        }
        else {
            cell.titleLable.text = @"厨房用品";
        }
        
        cell.iconImageView.image = [UIImage imageNamed:cell.titleLable.text];
        
        UIView *groupBackgroundView = [[UIView alloc] init];
        if ([UIScreen mainScreen].bounds.size.width <= 320.f) {
            groupBackgroundView.frame = CGRectMake(0, ([UIScreen mainScreen].bounds.size.width*BannerProportion)+38.f+10.f, self.view.frame.size.width, self.view.frame.size.width/2+40.f);
        }
        else {
            groupBackgroundView.frame = CGRectMake(0, ([UIScreen mainScreen].bounds.size.width*BannerProportion)+38.f+10.f, self.view.frame.size.width, self.view.frame.size.width/2);
        }
        groupBackgroundView.backgroundColor = [UIColor whiteColor];
        [self.collectionView addSubview:groupBackgroundView];
        [self.collectionView sendSubviewToBack:groupBackgroundView];
        
        return cell;
    }
    else if (indexPath.section == 3) {
        static NSString *ID = @"NiceStuffTitleCell";
        BCNiceStuffTitleCollectionViewCell *cell = [BCNiceStuffTitleCollectionViewCell cellWithCollectionView:collectionView];
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
        return cell;
    }
    else {
        static NSString *ID = @"NiceStuffCell";
        BCNiceStuffCollectionViewCell *cell = [BCNiceStuffCollectionViewCell cellWithCollectionView:collectionView];
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
        ShopGroup *group = self.groups[4];
        STUFF *model = group.items[indexPath.row];
        cell.stuffImageView.image = [UIImage imageNamed:model.icon];
        cell.stuffNameLable.text = model.name;
        cell.stuffDiscriptionLable.text = model.discribtion;
        cell.rmbLable.text = [NSString stringWithFormat:@"￥%@/%@",[model.price rounding:2],model.unit];
        cell.price = [NSString stringWithFormat:@"￥%@",[model.price rounding:2]];
        cell.unit = [NSString stringWithFormat:@"/%@",model.unit];
        [cell makeAttributedString];
        return cell;
    }
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section

{
    
    if (section == 0) {
        UIEdgeInsets top = {0,25,0,25};
        return top;
    }
    else if (section == 1) {
        UIEdgeInsets top = {5,0,5,0};
        return top;
    }
    else if (section == 2) {
        UIEdgeInsets top = {0,0,0,0};
        return top;
    }
    else if (section == 3) {
        UIEdgeInsets top = {5,0,1,0};
        return top;
    }
    else {
        UIEdgeInsets top = {0,5,self.rdv_tabBarController.tabBar.frame.size.height,5};
        return top;
    }
}

//定义每个UICollectionViewCell 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        return CGSizeMake(self.view.frame.size.width, self.view.frame.size.width*BannerProportion);
    }
    else if (indexPath.section == 1) {
        return CGSizeMake(self.view.frame.size.width, 38.f);
    }
    else if (indexPath.section == 2) {
        if ([UIScreen mainScreen].bounds.size.width <= 320.f) {
            return CGSizeMake(self.view.frame.size.width/4, self.view.frame.size.width/4+20.f);
        }
        else {
            return CGSizeMake(self.view.frame.size.width/4, self.view.frame.size.width/4);
        }
    }
    else if (indexPath.section == 3) {
        return CGSizeMake(self.view.frame.size.width, 25.f);
    }
    else {
        return CGSizeMake(self.view.frame.size.width, 122.f);
    }
    
}

//每个item之间的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    if (section == 0) {
        return 0;
    }
    else if (section == 1) {
        return 0;
    }
    else if (section == 2) {
        return 0;
    }
    else if (section == 3) {
        return 0;
    }
    else {
        return 0;
    }
}

//每个section中不同的行之间的行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    
    if (section == 0) {
        return 0;
    }
    else if (section == 1) {
        return 0;
    }
    else if (section == 2) {
        return 0;
    }
    else if (section == 3) {
        return 0;
    }
    else {
        return 1;
    }
}

//collectionview点击
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 2) {
        BCStuffChooseViewController *chooseController = [[BCStuffChooseViewController alloc] initWithIndex:indexPath.row];
        [self.navigationController pushViewController:chooseController animated:YES];
    }
    else if (indexPath.section == 4) {
        BCStuffInfoViewController *stuffInfoViewController = [[BCStuffInfoViewController alloc] init];
        ShopGroup *group = self.groups[4];
        STUFF *model = group.items[indexPath.row];
        stuffInfoViewController.stuff_uuid = model.uuid;
        [self.navigationController pushViewController:stuffInfoViewController animated:YES];
    }
}

#pragma mark - LJBannerCellDelegate
- (void)bannerCellClick:(BCBannerCell *)forumTitleView andWithBtnTag:(NSInteger)tag {
    
}

#pragma mark - action
/**
 *  选择城市点击方法
 */
- (void)p_choiceCity {
    NSLog(@"%s",__func__);
}

/**
 *  点击搜索框事件
 */
- (void)p_startSearch {
//    NSLog(@"%s",__func__);
    BCSearchResulfViewController *searchResultViewController = [[BCSearchResulfViewController alloc] init];
    [self.navigationController pushViewController:searchResultViewController animated:YES];
}

/**
 *  点击消息事件
 */
- (void)msgAction:(UIButton *)sender {
    BCMessageViewController *nextViewController = [[BCMessageViewController alloc] init];
    [self.navigationController pushViewController:nextViewController animated:YES];
}

- (void)initData {
    [self loadGroup0];
    [self loadGroup1];
    [self loadGroup2];
    [self loadGroup3];
    [self loadGroup4];
}

- (void)loadGroup0 {
    // 创建组, 以及每组内的模型
    ShopGroup *group0 = [[ShopGroup alloc] init];
    group0.items = @[@"0"];
    [self.groups addObject:group0];
}

- (void)loadGroup1 {
    // 创建组, 以及每组内的模型
    ShopGroup *group1 = [[ShopGroup alloc] init];
    group1.items = @[@"0"];
    [self.groups addObject:group1];
}

- (void)loadGroup2 {
    // 创建组, 以及每组内的模型
    ShopGroup *group2 = [[ShopGroup alloc] init];
    group2.items = @[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7"];
    [self.groups addObject:group2];
}

- (void)loadGroup3 {
    // 创建组, 以及每组内的模型
    ShopGroup *group3 = [[ShopGroup alloc] init];
    group3.items = @[@"0"];
    [self.groups addObject:group3];
}

- (void)loadGroup4 {
    // 创建组, 以及每组内的模型
    ShopGroup *group4 = [[ShopGroup alloc] init];
    group4.items = _stuffArray;
    [self.groups addObject:group4];
}

#pragma mark - Lazy
- (NSMutableArray *)groups {
    if (_groups == nil) {
        _groups = [NSMutableArray array];
    }
    return _groups;
}

- (UIView *)greenView {
    if (_greenView == nil) {
        _greenView = [[UIView alloc] init];
    }
    return _greenView;
}

@end
